------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

    晾晒架

]]--
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 素材
    local assets =
    {
        Asset("ANIM", "anim/hutao_building_drying_rack.zip"),
    }
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 参数表
    local MAX_PROCESS_TIMES = 4 -- 最大上色次数
    local HAT_DRYING_UPDATE_TIME = 2
    local ACCEPT_REQUIRE_HAT_PREFAB = "FF66FF__0XTT" -- 可接受的帽子预制体.
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- anim controller
    --[[
        empty_normal            -- 空闲
        can_be_harvested.petal  -- 是否可以收获花瓣
        can_be_harvested.hat  -- 是否可以收获帽子

        is_holding.petal  -- 是否持有花瓣
        is_holding.hat  -- 是否持有帽子

        need_coloring -- 需要上色
        need_not_coloring -- 不需要上色
    ]]
    local anim_fn = {
        ["empty_normal"] = function(inst)
            inst.AnimState:ClearOverrideSymbol("swap_dried")
            inst.AnimState:PlayAnimation("idle_empty")
        end,
        ["can_be_harvested.petal"] = function(inst)
            inst.AnimState:PlayAnimation("idle_full")
            inst.AnimState:OverrideSymbol("swap_dried","meat_rack_food", "monstermeat_dried")
        end,
        ["can_be_harvested.hat"] = function(inst)

        end,
        ["is_holding.petal"] = function(inst)
            inst.AnimState:PlayAnimation("idle_full")
            inst.AnimState:OverrideSymbol("swap_dried","meat_rack_food", "meat_dried")
        end,
        ["is_holding.hat"] = function(inst)

        end,
        ["need_coloring"] = function(inst)
            print("需要上色")
        end,
        ["need_not_coloring"] = function(inst)
            print("不需要上色")
        end,        
    }
    local function play_anim(inst,anim_index)
        if anim_fn[anim_index] then
            anim_fn[anim_index](inst)
        end
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 物品函数
    --[[
            正常产物：
            20%概率获得“玲珑饰物”  hutao_equipment_exquisite_ornament
            20%概率获得“巡之丘高中校服”， hutao_equipment_megurigaoka_private_high_school_uniform
            20%概率获得“抑郁少女的连衣帽”  hutao_equipment_black_hoodie_of_a_depressed_girl
            非正常产物：
            10%概率获得7个煤炭（煤花）  charcoal
            10%概率获得7个多汁浆果（莓花） berries_juicy
            10%概率获得2个梅花（梅开二度） hutao_item_plum_blossom_petal
            10%概率架子上的东西消失（没花） none
    ]]--
    local function havest_list_refresh(inst,new_table) -- 做多态函数，如果传入new_table则更新，否则返回储存值或默认值
        if new_table then
            inst.components.hutao_com_drying_module:Set("havest_petal_list",new_table)
        else
            return inst.components.hutao_com_drying_module:Get("havest_petal_list",{
                ["hutao_equipment_exquisite_ornament"] = 0.2,
                ["hutao_equipment_megurigaoka_private_high_school_uniform"] = 0.2,
                ["hutao_equipment_black_hoodie_of_a_depressed_girl"] = 0.2,
                ["charcoal"] = 0.1,
                ["berries_juicy"] = 0.1,
                ["hutao_item_plum_blossom_petal"] = 0.2,
                ["nil"] = 0.1,
            })
        end
    end
    local havest_reward_list = {
        ["charcoal"] = 7,
        ["berries_juicy"] = 7,
        ["hutao_item_plum_blossom_petal"] = 2,
        ["hutao_equipment_exquisite_ornament"] = 1,
    }

    local process_item = {
        ["featherpencil"] = function(inst,item,doer)
            -----------------------------------------------------
            -- 每用羽毛笔对架子上的梅花进行一次“上色”,增加10%成为玲珑饰物的概率，同时减少四种非正常产物的概率各2.5%
                local havest_list = havest_list_refresh(inst)
                havest_list["charcoal"] = havest_list["charcoal"] - 0.025
                havest_list["berries_juicy"] = havest_list["berries_juicy"] - 0.025
                havest_list["hutao_item_plum_blossom_petal"] = havest_list["hutao_item_plum_blossom_petal"] - 0.025
                havest_list["nil"] = havest_list["nil"] - 0.025
                havest_list["hutao_equipment_exquisite_ornament"] = havest_list["hutao_equipment_exquisite_ornament"] + 0.1
                havest_list_refresh(inst,havest_list)
            -----------------------------------------------------
            item.components.stackable:Get():Remove()
            inst:PushEvent("processed_init")
            return true
        end,
        ["sewing_kit"] = function(inst,item,doer)
            -----------------------------------------------------
            -- 每用缝纫包对架子上的梅花进行一次“缝制”（消耗一次缝纫包耐久），会增加10%成为巡之丘高中校服的概率。同时减少四种非正常产物的概率各2.5%
                local havest_list = havest_list_refresh(inst)
                havest_list["charcoal"] = havest_list["charcoal"] - 0.025
                havest_list["berries_juicy"] = havest_list["berries_juicy"] - 0.025
                havest_list["hutao_item_plum_blossom_petal"] = havest_list["hutao_item_plum_blossom_petal"] - 0.025
                havest_list["nil"] = havest_list["nil"] - 0.025
                havest_list["hutao_equipment_megurigaoka_private_high_school_uniform"] = havest_list["hutao_equipment_megurigaoka_private_high_school_uniform"] + 0.1
                havest_list_refresh(inst,havest_list)
            -----------------------------------------------------
            if item.components.finiteuses then
                item.components.finiteuses:Use()
            else
                item:Remove()
            end
            inst:PushEvent("processed_init")
            return true
        end,
        ["meat"] = function(inst,item,doer)
            -----------------------------------------------------
            -- 每用大肉块对架子上的梅花进行一次“过油”（消耗一块肉，小块也可，怪物肉不行），会增加10%成为抑郁少女的连衣帽的概率。同时减少四种非正常产物的概率各2.5%
                local havest_list = havest_list_refresh(inst)
                havest_list["charcoal"] = havest_list["charcoal"] - 0.025
                havest_list["berries_juicy"] = havest_list["berries_juicy"] - 0.025
                havest_list["hutao_item_plum_blossom_petal"] = havest_list["hutao_item_plum_blossom_petal"] - 0.025
                havest_list["nil"] = havest_list["nil"] - 0.025
                havest_list["hutao_equipment_black_hoodie_of_a_depressed_girl"] = havest_list["hutao_equipment_black_hoodie_of_a_depressed_girl"] + 0.1
                havest_list_refresh(inst,havest_list)
            -----------------------------------------------------
            item.components.stackable:Get():Remove()
            inst:PushEvent("processed_init")
            return true
        end,
    }
    --- 同类替换列表
    local process_item_replace = {
        ["smallmeat"] = "meat",
    }
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 干燥逻辑
    local function get_replaced_prefab(prefab)
        if process_item_replace[prefab] then
            return process_item_replace[prefab]
        end
        return prefab
    end
    local function on_accept_fn(inst,item,doer) -- 物品接受交互
        local temp_prefab = get_replaced_prefab(item.prefab)
        ------------------------------------------------------------------------
        --- 上色物品
            if process_item[temp_prefab] then
                if process_item[temp_prefab](inst,item,doer) then
                    inst.components.hutao_com_drying_module:Set("last_processed_day",TheWorld.state.cycles)
                    inst.components.hutao_com_drying_module:Add("processed_times",1)
                    inst:PushEvent("processed_init")
                    return true
                end
            end
        ------------------------------------------------------------------------
        --- 接受花瓣
            if temp_prefab == "hutao_item_plum_blossom_petal" then
                inst.components.hutao_com_drying_module:SetHarvest("hutao_item_plum_blossom_petal")
                item.components.stackable:Get():Remove()
                inst.components.hutao_com_drying_module:Set("start_day",TheWorld.state.cycles)
                inst.components.hutao_com_drying_module:Set("last_processed_day",TheWorld.state.cycles)
                inst.components.hutao_com_drying_module:SetHarvester(nil)
                inst:PushEvent("processed_init")
                return true
            end
        ------------------------------------------------------------------------
        --- 接受帽子
            if temp_prefab == ACCEPT_REQUIRE_HAT_PREFAB then
                --- 配置干燥时间
                inst.components.hutao_com_drying_module:Set("hat_dry_time",100)
                inst.components.hutao_com_drying_module:SetHarvest(ACCEPT_REQUIRE_HAT_PREFAB)
                inst.components.hutao_com_drying_module:SetHarvester(doer)
                if doer.components.hutao_com_cosmic_hat_sys_for_player then
                    doer.components.hutao_com_cosmic_hat_sys_for_player:SetHat(nil)
                    doer.components.hutao_com_cosmic_hat_sys_for_player:find_linked_drying_rack()
                end
                inst:PushEvent("processed_init")
                item:Remove()
                return true
            end
        ------------------------------------------------------------------------
        return false
    end
    local function on_work_fn(inst,doer) -- 采收交互
        if not inst.components.hutao_com_drying_module:CanHarvest(doer) then
            return false
        end
        inst.components.hutao_com_drying_module:DoHarvest(doer)
        return true
    end
    --- 花瓣采集函数。
    local function plum_blossom_petal_on_harvest(inst, doer)
        -- 重置处理次数为0
        inst.components.hutao_com_drying_module:Set("processed_times", 0)        
        -- 清除收获设置
        inst.components.hutao_com_drying_module:SetHarvest(nil)    
        -- 获取最新的收获目标列表
        local havest_target_list = havest_list_refresh(inst)        
        -- 初始化变量
        local cumulative_probability = 0
        local items = {}
        local probabilities = {}    
        -- 构建累计概率表
        for prefab, probability in pairs(havest_target_list) do
            table.insert(items, prefab)
            cumulative_probability = cumulative_probability + probability
            table.insert(probabilities, cumulative_probability)
        end    
        -- 根据累计概率选择一个物品
        local random_num = math.random() * cumulative_probability
        local selected_item = nil
        for i, prob in ipairs(probabilities) do
            if random_num <= prob then
                selected_item = items[i]
                break
            end
        end
        -- 如果选择了有效的物品，则给予doer
        if selected_item and PrefabExists(selected_item) then
            local num = havest_reward_list[selected_item] or 1
            for i = 1, num do
                doer.components.inventory:GiveItem(SpawnPrefab(selected_item))
            end
        end        
        -- 触发处理初始化事件
        inst:PushEvent("processed_init")
    end
    --- 帽子的采集函数
    local function hat_on_harvest(inst, doer)
        inst.components.hutao_com_drying_module:Set("hat_dry_time",0)
        inst.components.hutao_com_drying_module:SetHarvest(nil)
        inst.components.hutao_com_drying_module:SetHarvester(nil)

        -- doer.components.inventory:GiveItem(SpawnPrefab(ACCEPT_REQUIRE_HAT_PREFAB))
        if doer.components.hutao_com_cosmic_hat_sys_for_player then
            doer.components.hutao_com_cosmic_hat_sys_for_player:find_linked_drying_rack()   -- 刷一次帽子
            doer.components.hutao_com_cosmic_hat_sys_for_player:CallHat()
        end

        inst:PushEvent("processed_init")
    end
    --- 周期性检查
    local function day_cycle_task(inst)
        inst:PushEvent("processed_init")
    end

    local function drying_module_install(inst)
        inst:AddComponent("hutao_com_drying_module")
        inst.components.hutao_com_drying_module:SetHarvestFn("hutao_item_plum_blossom_petal",plum_blossom_petal_on_harvest)
        inst.components.hutao_com_drying_module:SetHarvestFn(ACCEPT_REQUIRE_HAT_PREFAB,hat_on_harvest)
        inst:WatchWorldState("cycles",day_cycle_task)
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 帽子的干燥任务
    local function hat_drying_task(inst)
        if not inst.components.hutao_com_drying_module:GetCurrent() == ACCEPT_REQUIRE_HAT_PREFAB then
            TheWorld.components.hutao_com_special_timer_for_theworld:RemoveTimer(inst)
            return
        end
        local last_drying_time = 0
        -- HAT_DRYING_UPDATE_TIME
        if TheWorld.state.israining then
            --- 如果是雨天，则增加时间。最多 1554秒
            last_drying_time = inst.components.hutao_com_drying_module:Add("hat_dry_time",HAT_DRYING_UPDATE_TIME,0,1554)
        else
            --- 如果附近有热源，则加速干燥
            if inst.components.hutao_com_flower_switcher:IsNearHotSource(7) then
                last_drying_time = inst.components.hutao_com_drying_module:Add("hat_dry_time",-HAT_DRYING_UPDATE_TIME*2)
            else
                last_drying_time = inst.components.hutao_com_drying_module:Add("hat_dry_time",-HAT_DRYING_UPDATE_TIME)
            end
        end
        print("剩余干燥时间",last_drying_time)
        inst:PushEvent("processed_init")
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 总初始化和状态切换
    local function drying_building_init(inst)
        --------------------------------------------------------
        --- 动画
            play_anim(inst,"empty_normal")
        --------------------------------------------------------
        --- 物品接受检查配置
            local current_item_prefab = inst.components.hutao_com_drying_module:GetCurrent()
            if current_item_prefab == nil then
                --- 空物品的时候，允许接受 花瓣 和 帽子
                inst.components.hutao_com_drying_module:ClearAccept()
                inst.components.hutao_com_drying_module:AddAccept("hutao_item_plum_blossom_petal",STRINGS.ACTIONS.DRY)
                inst.components.hutao_com_drying_module:AddAccept(ACCEPT_REQUIRE_HAT_PREFAB,STRINGS.ACTIONS.DRY)
            elseif current_item_prefab == ACCEPT_REQUIRE_HAT_PREFAB then
                inst.components.hutao_com_drying_module:ClearAccept()
                play_anim(inst,"is_holding.hat")
            elseif current_item_prefab == "hutao_item_plum_blossom_petal" then
                    play_anim(inst,"is_holding.petal")
                    --- 挂的是花瓣的时候。
                    inst.components.hutao_com_drying_module:ClearAccept()   --- 清空当前可接受列表
                    if inst.components.hutao_com_drying_module:Get("last_processed_day",TheWorld.state.cycles) ~= TheWorld.state.cycles then
                        --- 添加可接受物品。
                        local process_times = inst.components.hutao_com_drying_module:Add("processed_times",0)
                        if process_times < MAX_PROCESS_TIMES then
                            for k, v in pairs(process_item) do
                                inst.components.hutao_com_drying_module:AddAccept(k,TUNING.HUTAO_FNS:GetString(inst.prefab,"coloring") or STRINGS.ACTIONS.CRAFT)                        
                            end
                            play_anim(inst,"need_coloring")
                        end
                    end
            end
        --------------------------------------------------------
        --- 采收
            if current_item_prefab == nil then
                inst.components.hutao_com_workable:SetCanWorlk(false)
                TheWorld.components.hutao_com_special_timer_for_theworld:RemoveTimer(inst)
            elseif current_item_prefab == ACCEPT_REQUIRE_HAT_PREFAB then
                if inst.components.hutao_com_drying_module:Add("hat_dry_time",0) <= 0 then
                    TheWorld.components.hutao_com_special_timer_for_theworld:RemoveTimer(inst)
                    play_anim(inst,"can_be_harvested.hat")
                    inst.components.hutao_com_workable:SetCanWorlk(true)
                else
                    TheWorld.components.hutao_com_special_timer_for_theworld:AddTimer(inst,hat_drying_task,HAT_DRYING_UPDATE_TIME)
                end
            elseif current_item_prefab  == "hutao_item_plum_blossom_petal" then
                if math.abs(inst.components.hutao_com_drying_module:Add("start_day",0) - TheWorld.state.cycles) > 3 then
                    inst.components.hutao_com_workable:SetCanWorlk(true)
                    play_anim(inst,"can_be_harvested.petal")
                else
                    inst.components.hutao_com_workable:SetCanWorlk(false)
                end
                TheWorld.components.hutao_com_special_timer_for_theworld:RemoveTimer(inst)
            end
        --------------------------------------------------------        
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 通用物品接受组件
    local function accept_test_fn(inst,item,doer,right_click)
        if inst.replica.hutao_com_drying_module == nil then
            return false
        end
        local can_accept,txt_index = inst.replica.hutao_com_drying_module:CanAccept(item.prefab)
        inst.replica.hutao_com_acceptable:SetText(inst.prefab,txt_index)
        return can_accept
    end
    local function acceptable_replica_init(inst,replica_com)
        replica_com:SetText("hutao_building_drying_rack","")
        replica_com:SetSGAction("dolongaction")
        replica_com:SetTestFn(accept_test_fn)
    end

    local function acceptable_com_install(inst)
        inst:ListenForEvent("HUTAO_OnEntityReplicated.hutao_com_acceptable",acceptable_replica_init)
        if not TheWorld.ismastersim then
            return
        end
        inst:AddComponent("hutao_com_acceptable")
        inst.components.hutao_com_acceptable:SetOnAcceptFn(on_accept_fn)        
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 物品采集模块
    local function workable_test_fn(inst,doer,right_click)
        if inst.replica.hutao_com_drying_module == nil then
            return false
        end
        return inst.replica.hutao_com_drying_module:CanHarvest(doer)
    end
    local function workable_replica_init(inst,replica_com)
        replica_com:SetTestFn(workable_test_fn)
        replica_com:SetSGAction("dolongaction")
        replica_com:SetText("hutao_building_drying_rack",STRINGS.ACTIONS.PICK.HARVEST)
    end
    local function worlabke_com_install(inst)
        inst:ListenForEvent("HUTAO_OnEntityReplicated.hutao_com_workable",workable_replica_init)
        if not TheWorld.ismastersim then
            return
        end
        inst:AddComponent("hutao_com_workable")
        inst.components.hutao_com_workable:SetOnWorkFn(on_work_fn)
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- building
    local function building_fn()
        local inst = CreateEntity()

        inst.entity:AddTransform()
        inst.entity:AddAnimState()
        inst.entity:AddMiniMapEntity()
        inst.entity:AddSoundEmitter()
        inst.entity:AddNetwork()

        -- inst.MiniMapEntity:SetIcon("meatrack.png")

        inst:AddTag("structure")
        inst:AddTag("hutao_building_drying_rack")
        inst.AnimState:SetBank("meatrack_hermit")
        inst.AnimState:SetBuild("hutao_building_drying_rack")
        inst.AnimState:PlayAnimation("idle_empty")
        inst.entity:SetPristine()
        ------------------------------------------------------------
        --- 模块安装
            acceptable_com_install(inst)
            worlabke_com_install(inst)
        ------------------------------------------------------------
        if not TheWorld.ismastersim then
            return inst
        end
        ------------------------------------------------------------
        --- 
            inst:AddComponent("hutao_com_flower_switcher")
            inst.components.hutao_com_flower_switcher:SetIsFlower(false)
        ------------------------------------------------------------
        --- 
            inst:AddComponent("inspectable")
            MakeHauntableWork(inst)
            MakeMediumBurnable(inst, nil, nil, true)
            MakeSmallPropagator(inst)
        ------------------------------------------------------------
        -- 干燥模块
            drying_module_install(inst)
        ------------------------------------------------------------
        --
            inst:DoTaskInTime(0,drying_building_init)
            inst:ListenForEvent("processed_init",drying_building_init)
            inst:WatchWorldState("cycles",drying_building_init)
        ------------------------------------------------------------
        return inst
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
--- make placer
    local function placer_postinit_fn(inst)
        inst.AnimState:Hide("mouseover")
    end
------------------------------------------------------------------------------------------------------------------------------------------------------------
return Prefab("hutao_building_drying_rack",building_fn, assets),
    MakePlacer("hutao_building_drying_rack_placer", "meatrack_hermit", "hutao_building_drying_rack", "idle_empty", nil, nil, nil, nil, nil, nil, placer_postinit_fn, nil, nil)

